package com.lib76.buildCode.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VelocityServer {
	
	public final static String RESOURCE_PATH_KEY = "file.resource.loader.path";
	
	//初始化并取得Velocity引擎
	private static VelocityEngine engine;

	public static boolean initial(Properties prop){
		engine = new VelocityEngine();
		engine.init(prop);
		return true;
	}
	
	public static boolean initial(String cfgPath,String rootPath){
		if(StringUtils.isNotBlank(cfgPath)){
			Properties prop = new Properties();
			try {
				prop.load(FileUtils.openInputStream(new File(cfgPath)));
				prop.setProperty(VelocityServer.RESOURCE_PATH_KEY, rootPath + prop.getProperty(VelocityServer.RESOURCE_PATH_KEY));
				return initial(prop);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public static boolean initial(InputStream input,String rootPath){
		if(input != null){
			Properties prop = new Properties();
			try {
				prop.load(input);
				prop.setProperty(VelocityServer.RESOURCE_PATH_KEY, rootPath + prop.getProperty(VelocityServer.RESOURCE_PATH_KEY));
				return initial(prop);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public static void merge(String filePath,String template,VelocityContext context){
		try{
			if(StringUtils.isNotBlank(filePath)){
				File file = new File(filePath);
				if(file.exists() || file.createNewFile()){
					FileWriterWithEncoding writer = new FileWriterWithEncoding(file,"UTF-8");
					//取得velocity的模版
					Template t = engine.getTemplate(template);
					//转换输出
					t.merge(context, writer);
					writer.flush();
					writer.close();
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
}
